package com.hxzy.bbs.servlet;

import java.io.File;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.classic.Session;

import com.hxzy.jsp.connection.JNDIBBSConection;
import com.hxzy.jsp.entity.Post;
import com.hxzy.jsp.entity.User;
import com.mysql.jdbc.StringUtils;

public class PostTest extends AppServlet {

	private static final long serialVersionUID = 1L;
	private static List<String> suffix=null;
	public PostTest(){
	super();	
	}
	
	@Override
	public void init(ServletConfig config) throws ServletException {
		// TODO Auto-generated method stub
		String suf=config.getInitParameter("suffix");
		if(StringUtils.isEmptyOrWhitespaceOnly(suf)){
			throw new IllegalAccessError();
		}
		suffix=Arrays.asList(suf.toLowerCase().split(","));
	}
	@Override
	protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		if (request.getSession().getAttribute("user")== null) {
			response.sendRedirect("./login");
			return;
		}
		super.service(request, response);
	}
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.getRequestDispatcher("/WEB-INF/post.jsp").forward(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		
			boolean isMultipart = ServletFileUpload.isMultipartContent(request);
			if (!isMultipart) {
				response.sendRedirect("./error");
				return;
			}
			FileItemFactory factory = new DiskFileItemFactory();
			ServletFileUpload upload = new ServletFileUpload(factory);
			Map<String, String> formFields = new HashMap<String, String>();
			try {
				//解析form表单中所有文件
				List<FileItem> items = upload.parseRequest(request);
				Iterator<FileItem> iter = items.iterator();
				while (iter.hasNext()) { //依次处理每个文件
					FileItem item = (FileItem) iter.next();
					if (item.isFormField()) { //普通表单字段
						formFields.put(item.getFieldName(), item.getString("utf-8"));
					} else { //文件表单字段
						String fileName = item.getName();
						if (fileName != null && !fileName.equals("")) {
							File fullFile = new File(item.getName());
							File saveFile = new File(request.getServletContext().getRealPath("upload/"),
									fullFile.getName());
							item.write(saveFile);
							formFields.put(item.getFieldName(),
									String.format("%s://%s:%s%s/upload/%s", request.getScheme(),
											request.getServerName(), request.getServerPort(),
											request.getContextPath(), item.getName()));
						}
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			String title = formFields.get("title");
			String content = formFields.get("content");
			String keywords = formFields.get("keywords");
			String picUrl = formFields.get("pic_url");
			if (StringUtils.isEmptyOrWhitespaceOnly(title)) {
				response.sendRedirect("./error");
				return;
			}
			if (StringUtils.isEmptyOrWhitespaceOnly(content)) {
				response.sendRedirect("./error");
				return;
			}
			if (StringUtils.isEmptyOrWhitespaceOnly(keywords)) {
				response.sendRedirect("./error");
				return;
			}

			User userInSession = (User) request.getSession().getAttribute("user");
			Connection conn = null;
			try {
				long NOW = Calendar.getInstance().getTimeInMillis() / 1000;
				
				Configuration configuration = new Configuration().configure();
				SessionFactory factory1 = configuration.buildSessionFactory();
				Session session = factory1.openSession();
				Transaction tx=session.getTransaction();
				Post post=new Post();
				post.setContent(content);
				post.setTitle(title);
				post.setKeywords(keywords);
				post.setUserId(userInSession.getId());
				post.setUserNickname(userInSession.getNickname());
				post.setHits((long) 0);
				post.setLike((long) 0);
				post.setIp(request.getRemoteAddr());
				post.setGmtCreate(NOW);
				post.setGmtModified(NOW);
				post.setPicUrl(picUrl);
				session.merge(post);
				tx.commit();
				
			} catch (Exception e) {
				e.printStackTrace();
				response.sendRedirect("./error");
				return;
			} finally {
				try {
					conn.close();
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		response.sendRedirect("./index");
}

}

